package com.frcdi.qms.common.config.jdbc;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @ClassName JdbcUtils
 * @Author Mr.Han
 * @Description //TODO jdbc工具类$
 * @create 2024/5/20 16:29
 **/
@Component
public class JdbcUtils {

   /* @Autowired
    private Environment environment;*/

    @Value("${spring.datasource.druid.master.url}")
    String databaseBackupUrl;

    @Value("${spring.datasource.druid.master.username}")
    String databaseBackupUsername;

    @Value("${spring.datasource.druid.master.password}")
    String databaseBackupPassword;


    @Value("${spring.datasource.druid.master.url}")
    String databaseTransferUrl;

    @Value("${spring.datasource.druid.master.username}")
    String databaseBackupTransferUsername;

    @Value("${spring.datasource.druid.master.password}")
    String databaseBackupTransferPassword;


    public HashMap<String, String> getDatabaseBackupDBInfo() {
        //String url = environment.getProperty("test.url");//("spring.datasource.druid.master.url");
        //String username = environment.getProperty("test.username");//("spring.datasource.druid.master.username");
        //String password = environment.getProperty("test.password");//("spring.datasource.druid.master.password");
        return getDBInfo(databaseBackupUrl,databaseBackupUsername,databaseBackupPassword);
    }
    public HashMap<String, String> getDatabaseTransferDBInfo() {

        return getDBInfo(databaseTransferUrl,databaseBackupTransferUsername,databaseBackupTransferPassword);
    }
    private HashMap<String, String> getDBInfo(String url,String username,String password) {
        // 去掉前缀
        String urlWithoutPrefix = url.replaceFirst("jdbc:mysql://", "");

        // 分割剩余的 URL 字符串
        String[] split = urlWithoutPrefix.split(":");
        String host = split[0];
        String[] portSplit = split[1].split("/");
        String port = portSplit[0];

        String[] databaseSplit = portSplit[1].split("\\?");
        String dbName = databaseSplit[0];

        HashMap<String, String> result = new HashMap<>();
        result.put("url", url);
        result.put("host", host);
        result.put("port", port);
        result.put("dbName", dbName);
        result.put("userName", username);
        result.put("passWord", password);

        return result;
    }
}

